// pages/me/changePwd/changePwd2.js
import * as API from '../../../api/loginApi';
import * as util from '../../../utils/util';
import { clearLoginStatus, redirect } from '../../../utils/auth';

let app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    repeatPassword: '',
    newPassword: '',
    phone: '',
    authorizationCode: ''
  },

  bindKeyInput: function (e) {
    var name = e.currentTarget.dataset.name
    this.setData({
      [name]: e.detail.value
    });
  },

  formSubmit: function (e) {
    util.preventMoreClick(this, () => {
      if (!this.validatePassword(e)) return;
      let password = this.data.newPassword
      let authorizationCode = this.data.authorizationCode
      API.findPassword(password, authorizationCode).then(res => {
        util.toast('密码修改成功!');
        setTimeout(() => {
          this.logout();
        }, 1000);
      }, err => {
        util.toast(err || '修改失败,请稍后再试');
        this.setData({
          repeatPassword: '',
          newPassword: ''
        });
      });
    });
  },
  logout() {
    // logout
    let token = wx.getStorageSync('token');
    API.logout(token).then(res => {
      this.afterLogout();
    }, err => {
      this.afterLogout();
    });
  },
  afterLogout() {
    clearLoginStatus();
    wx.reLaunch({
      url: '/pages/login/login',
      complete: function () {
        wx.hideTabBarRedDot({
          index: 1
        });
      }
    });
  },
  validatePassword(e) {
    var repeatPassword = e.detail.value.repeatPassword;
    var newPassword = e.detail.value.newPassword;
    if (repeatPassword != newPassword) {
      util.toast('密码输入不一致');
      return false;
    }
    // if (!util.validators.pwd2.test(newPassword)) {
    //   util.toast('密码格式错误');
    //   return false;
    // }
    if (!util.validators.pwd.test(newPassword)) {
      util.toast('密码格式错误');
      return false;
    }
    return true;
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      phone: options.phone,
      authorizationCode: options.authorizationCode
    });
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  }

});